#!/bin/bash

usage(){
    cat <<'EOF'
                      项目名   后端IP   后端端口
    ./nginx_proxy.sh $project $back_ip $back_port

    ./nginx_proxy.sh jenkins 172.31.31.210 80
EOF
}

add_nginx_proxy () {
    cd /usr/local/nginx-1.17.3/conf.d/
    project="$1"
    back_ip="$2"
    back_port="$3"
    back_ip_num="$(echo "$back_ip" | cut -d '.' -f 4)"
    num=1
    while [ -f ${project}${back_ip_num}0${num}.conf ]; do
        let num+=1
    done
    cat > ${project}${back_ip_num}0${num}.conf <<-EOF
    upstream ${project}${back_ip_num}0${num} {
        server ${back_ip}:${back_port};
    }

    server {
        listen       ${back_ip_num}0${num};
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            proxy_pass http://${project}${back_ip_num}0${num};
            proxy_set_header Host \$host;
            proxy_set_header X-Real-IP \$remote_addr;
            proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
            proxy_set_header X-NginX-Proxy true;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
          root   html;
        }
    }
EOF

    # reload nginx
    /usr/local/nginx-1.17.3/sbin/nginx -s reload

    # firewalld
    port="${back_ip_num}0${num}"
    firewall-cmd --zone=public --add-port=${port}/tcp --permanent
    firewall-cmd --reload
    firewall-cmd --list-port| grep ${port}

    # out info
    cat <<-EEOF
    ---------------------------------------------------------
    back_ip: $back_ip
    back_port: $back_port
    public_url: 122.114.2.195:${port}
    nginx_conf_file_path: /usr/local/nginx-1.17.3/conf.d/${project}${back_ip_num}0${num}.conf
EEOF
}

[ $# -ne 3 ] && { USAGE; exit 1; }
add_nginx_proxy